from flask import request
from flask_restx import Resource
from werkzeug.security import check_password_hash

from app import db
from app.models.user import User
from app.utils.jwt_utils import decode_token
from app.protocols import response_model, user_ns, user_update_model, user_delete_model


@user_ns.route('/')
class UserInfo(Resource):
    @user_ns.marshal_with(response_model)
    def get(self):
        """获取用户信息"""
        user_id = request.user_id
        user = User.query.get(user_id)
        if not user:
            user_ns.abort(404, message='用户不存在')

        return {
            'message': '获取用户信息成功',
            'data': {
                'id': user.id,
                'username': user.username,
                'email': user.email
            }
        }, 200

    @user_ns.expect(user_update_model)
    @user_ns.marshal_with(response_model)
    def put(self):
        """修改用户信息"""
        user_id = request.user_id
        user = User.query.get(user_id)
        if not user:
            user_ns.abort(404, message='用户不存在')

        # 获取请求数据
        data = request.get_json()
        username = data.get('username')
        email = data.get('email')

        # 更新字段（仅更新提供的字段）
        if username:
            user.username = username
        if email:
            # 可选：检查邮箱是否已被其他用户使用
            existing_user = User.query.filter(User.email == email, User.id != user_id).first()
            if existing_user:
                user_ns.abort(400, message='邮箱已被使用')
            user.email = email

        # 如果没有提供任何字段，返回错误
        if not username and not email:
            user_ns.abort(400, message='至少提供一个字段')

        # 保存更改到数据库
        try:
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            user_ns.abort(500, message=f'更新失败: {str(e)}')

        return {
            'message': '用户信息更新成功',
            'data': {
                'id': user.id,
                'username': user.username,
                'email': user.email
            }
        }, 200

    @user_ns.expect(user_delete_model)
    @user_ns.marshal_with(response_model)
    def delete(self):
        """删除用户"""
        user_id = request.user_id
        user = User.query.get(user_id)
        if not user:
            user_ns.abort(404, message='用户不存在')

        data = request.get_json()
        password = data.get('password')

        if not check_password_hash(user.password, password):
            user_ns.abort(401, message='密码错误')

        # 调用软删除方法
        user.delete()

        return {'message': '用户注销成功'}, 200
